package com.xcdh.learn.controller;

import com.xcdh.commons.controller.BaseController;
import com.xcdh.domain.vo.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/chat")
public class ChatGptController  {

    private static final String API_URL = "https://api.openai.com/v1/moderations";

    @Value("${chatGptKey}")
    private String chatGptKey ;



    @PostMapping("/completion")
    public R<Object> getCompletion(@RequestParam String text) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Authorization", "Bearer " + chatGptKey);
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("text", text);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(API_URL, request, String.class);
        if (response.getStatusCodeValue() == 200) {
            Object result = response.getBody();
            System.out.println(result);
            return R.okData(result) ;
        } else {
            return R.error("Failed to call the moderation API.") ;
        }
    }
}
